package com.lengxf.pay.starter.parent.pay;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.lengxf.pay.common.enums.PayChannel;
import com.lengxf.pay.common.service.BasePayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class PayServiceFinder {

    private final PayServiceConfigFinder payServiceConfigFinder;

    private final List<PayServiceRegister> payServiceList;

    public PayServiceFinder(@Autowired(required = false) PayServiceConfigFinder payServiceConfigFinder,
                            @Autowired(required = false) List<PayServiceRegister> payServiceList) {
        Assert.notNull(payServiceConfigFinder);
        Assert.notEmpty(payServiceList);
        this.payServiceConfigFinder = payServiceConfigFinder;
        this.payServiceList = payServiceList;
    }

    public BasePayService find(String id, Map<String, String> attr) {
        ChannelConfig channelConfig = payServiceConfigFinder.find(id, attr);
        return find(channelConfig.getPayChannel(), channelConfig.getConfig());
    }

    public BasePayService find(String id) {
        ChannelConfig channelConfig = payServiceConfigFinder.find(id, MapUtil.empty());
        return find(channelConfig.getPayChannel(), channelConfig.getConfig());
    }

    public BasePayService find(PayChannel payChannel, String config) {
        return payServiceList.stream().filter(e -> e.payChannel().equals(payChannel))
                .findFirst().orElseThrow(() -> new RuntimeException(
                        String.format("No implements of { %s } payChannel", payChannel)))
                .payService(config);
    }

}
